package org.pupil.angryweather.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {

	public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				HttpURLConnection conn = null;
				try {
					URL url = new URL(address);
					conn = (HttpURLConnection) url.openConnection();
					conn.setRequestMethod("GET");
					conn.setReadTimeout(8000);
					conn.setConnectTimeout(8000);
					BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
					StringBuilder sb = new StringBuilder();
					String line = "";
					while ((line=reader.readLine()) != null) {
						sb.append(line);
					}
					if(listener != null){
						listener.onFinish(sb.toString());
					}
				} catch (Exception e) {
					if(listener != null){
						listener.onError(e);
					}
				} finally {
					if(conn != null){
						conn.disconnect();
					}
				}
			}
		}).start();
	}
	
	public static void main(String[] args) {
		sendHttpRequest("http://www.weather.com.cn/data/list3/city.xml", new HttpCallbackListener() {
			
			@Override
			public void onFinish(String response) {
				System.out.println(response);
			}
			
			@Override
			public void onError(Exception e) {
				e.printStackTrace();
			}
		});
	}

}
